package com.my.easypoi.test.simple;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;

import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class Exce3 {
    /*封装导出*/
    public static void main(String[] args) throws Exception {
        String title = "[{\"title\":\"报备人员\",\"width\":4000},{\"title\":\"性别\",\"width\":4000},{\"title\":\"年龄\",\"width\":4000},{\"title\":\"联系方式\",\"width\":4000},{\"title\":\"身份证号码\",\"width\":6000},{\"title\":\"抗原检测结果\",\"width\":4000},{\"title\":\"现住址(街道+具体地址)\",\"width\":6000},{\"title\":\"年月日\",\"width\":6000},{\"title\":\"年月日时分秒\",\"width\":10000}]";
        String fieldName = "[{\"fieldName\":\"name\"},{\"fieldName\":\"sex\"},{\"fieldName\":\"age\",\"type\":\"Integer\"},{\"fieldName\":\"mobile\"},{\"fieldName\":\"cardNo\"},{\"fieldName\":\"result\"},{\"fieldName\":\"address\"},{\"fieldName\":\"startTime\",\"type\":\"Date\",\"format\":\"yyyy年MM月dd日\"},{\"fieldName\":\"endTime\",\"type\":\"Date\",\"format\":\"yyyy年MM月dd日 HH时mm分ss秒\"}]";
        String list = "[{\"name\":\"张三\",\"sex\":\"男\",\"age\":18,\"mobile\":\"13900009999\",\"cardNo\":\"510105199909090009\",\"result\":\"阳性\",\"address\":\"古城社区9527号\",\"startTime\":\"\",\"endTime\":\"\"}]";
//        cn.hutool.json.JSONArray title = JSONUtil.parseArray(title);
        JSONArray titlejsonArray = JSONObject.parseArray(title);
        JSONArray fieldNamejsonArray = JSONObject.parseArray(fieldName);
        JSONArray listjsonArray = JSONObject.parseArray(list);
        exportExcel(listjsonArray,"示例.xls",titlejsonArray,fieldNamejsonArray);
    }

    public static void exportExcel(
//            HttpServletResponse response,
                            List list, String sheetName, List title, List field) throws Exception{
        String sheetStr = sheetName.substring(0, sheetName.lastIndexOf("."));
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet(sheetStr);
        //title样式
        HSSFCellStyle titleStyle = wb.createCellStyle();
        titleStyle.setAlignment(HorizontalAlignment.CENTER);
        titleStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        titleStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

//        String[] title = {"报备人员","性别","年龄","联系方式","身份证号码","抗原检测结果","现住址(街道+具体地址)","报备时间"};
        JSONArray titles = JSON.parseArray(JSONObject.toJSONString(title));
        JSONArray fields = JSON.parseArray(JSONObject.toJSONString(field));
        createExcelTitle(sheet, titles,titleStyle);
        if (CollectionUtils.isNotEmpty(list)){
            HSSFCellStyle valueStyle = wb.createCellStyle();
            valueStyle.setAlignment(HorizontalAlignment.CENTER);
            valueStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            //超长自动换行
            valueStyle.setWrapText(true);
            setExcelRowValue(sheet,list,valueStyle,fields);
        }
//        response.setHeader("content-type","application/vnd.ms-excel");
//        response.setHeader("character-encoding","ISO-8859-1");
//        String fileName = "测试";
//        String fileName = EncodeUtil.encodeFileName(sheetName, request);
//        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
//        response.setHeader("Access-Control-Allow-Origin", "*");
//        response.setHeader("Content-Disposition","attachment;filename="+fileName);
//        wb.write(response.getOutputStream());

        FileOutputStream fos = new FileOutputStream("D:\\ccc.xls");
        wb.write(fos);
        fos.close();
    }


    public static void createExcelTitle(HSSFSheet sheet, JSONArray title, HSSFCellStyle cellStyle) {
        HSSFRow row = sheet.createRow(0);
        for(int i=0;i<title.size();i++){
            JSONObject titleObj = title.getJSONObject(i);
            sheet.setColumnWidth(i,titleObj.getInteger("width"));
            HSSFCell cell = row.createCell(i);
            cell.setCellValue(titleObj.getString("title"));
            cell.setCellStyle(cellStyle);
        }
    }

    public static void setExcelRowValue(HSSFSheet sheet, List list, HSSFCellStyle valueStyle, JSONArray field) throws Exception{
        for(int i=0;i<list.size();i++){
            AtomicInteger index = new AtomicInteger(-1);
            HSSFRow row = sheet.createRow(i + 1);
            JSONObject jsonObject = (JSONObject)JSONObject.toJSON(list.get(i));
            for (int j=0;j<field.size();j++){
                HSSFCell cell = row.createCell(index.incrementAndGet());
                JSONObject fieldInfo = field.getJSONObject(j);
                String fieldName = fieldInfo.getString("fieldName");
                String fieldType = fieldInfo.getString("type");
                if ("Date".equals(fieldType)){
                    String format = fieldInfo.getString("format");
                    SimpleDateFormat dateFormat = new SimpleDateFormat(format);
                    if(jsonObject.getDate(fieldName)==null){
                        cell.setCellValue(dateFormat.format(new Date()));
                    }else{
                        cell.setCellValue(dateFormat.format(jsonObject.getDate(fieldName)));
                    }
                }else if ("Integer".equals(fieldType)){
                    cell.setCellValue(jsonObject.getInteger(fieldName));
                }else if ("Long".equals(fieldType)){
                    cell.setCellValue(jsonObject.getLong(fieldName));
                }else {
                    cell.setCellValue(jsonObject.getString(fieldName));
                }
                cell.setCellStyle(valueStyle);
            }
        }
    }
}
